<template>
  <view class="homeBox">
    <z-paging
      ref="paging"
      :emptyViewErrorText="errTitle"
      v-model="products"
      :auto="false"
      :default-page-size="20"
      class="warpper"
      lower-threshold="500px"
      :auto-hide-loading-after-first-loaded="false"
      safe-area-inset-bottom
      use-safe-area-placeholder
      @query="queryProducts"
      @onRefresh="onRefresh"
      @scroll="handlePagingScroll"
      :refresher-complete-delay="800"
      refresher-complete-text="刷新成功"
    >
      <template #top>
        <view class="search-box" :class="{ tops: isTop }">
          <view @click="back" class="back" :class="{ topcr: isTop }">
            <image src="@/assets/icon-back.png"></image>
          </view>
          <view class="navbar-content" :class="{ isctop: isTop }">
            <view class="logomerbo"
              ><image
                class="game-logo"
                @click="selectGameGroup"
                :src="gameLogo"
              ></image
            ></view>
            <input
              class="search"
              type="text"
              ref="searchInput"
              v-model="searchValue"
              autofocus
              placeholder="请输入搜索词"
            />
            <view @click="paging.reload()" class="search-icon">
              <image src="@/assets/search-icon.svg"></image>
            </view>
          </view>
        </view>
        <view v-show="isTop" class="game-filter noread">
          <view
            @click="showDetils"
            :class="{
              sortactive: sortItem.index !== 0 && sortItem.index,
              topleft: isTop,
            }"
            class="left"
          >
            {{ sortItem.name || "默认排序" }}
            <image
              :class="{ rotate180: sortItem.icon === 'up' }"
              src="@/assets/filter-d.svg"
            ></image>
          </view>
          <view @click="showFilter" class="right">
            筛选
            <image src="@/assets/filter-l.svg"></image>
          </view>
        </view>
      </template>
      <view ref="gameFilter">
        <view v-if="!isTop" :class="{ 'my-top': !isTop }" class="game-filter">
          <view
            @click="showDetils"
            :class="{ sortactive: sortItem.index !== 0 && sortItem.index }"
            class="left"
          >
            {{ sortItem.name || "默认排序" }}
            <image
              :class="{ rotate180: sortItem.icon === 'up' }"
              src="@/assets/filter-d.svg"
            ></image>
          </view>
          <view @click="showFilter" class="right">
            筛选
            <image src="@/assets/filter-l.svg"></image>
          </view>
        </view>
      </view>
      <view class="content">
        <game-item
          @click="toDetils(item)"
          v-for="item in products"
          :data="item"
        ></game-item>
      </view>
      <template #empty>
        <view class="no-data">
          <image src="@/assets/not-data.png"></image>
          <view class="not-info">暂无在售商品哦~</view>
        </view>
      </template>
    </z-paging>
    <!-- 更多游戏 -->
    <uni-popup
      @close="closeGameGroup"
      @maskClick="closeGameGroup"
      ref="morePopupRef"
      type="bottom"
    >
      <view class="group-content-game">
        <image
          @click="closeGameGroup"
          class="close-game"
          src="@/assets/close.svg"
        ></image>
        <view class="all-game">全部游戏</view>
        <view class="game-list">
          <view
            @click="toMoreGame(item, index)"
            v-for="(item, index) in gameList"
            :key="index"
            class="item-game"
          >
            <view :class="{ active: index == activeItem }" class="game-ico"
              ><image :src="item.game_pic"></image
            ></view>
            <view
              :class="{ selectgame: index == activeItem }"
              class="game-name-value"
              >{{ item.game_name }}</view
            >
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 排序弹框 -->
    <uni-popup
      @close="closeDetils"
      @maskClick="closeDetils"
      ref="popupRef"
      type="bottom"
    >
      <view class="group-content">
        <view class="sort-list">
          <view
            @click="sortContent(item, index)"
            :class="{ sortactive: sortItem.index == index }"
            v-for="(item, index) in sortList"
            >{{ item.name }}</view
          >
        </view>
      </view>
    </uni-popup>
    <!-- 筛选 -->
    <uni-popup
      @close="closeFilterGroup"
      @maskClick="closeFilterGroup"
      ref="filterPopupRef"
      type="bottom"
    >
      <view class="group-content-game">
        <image
          @click="closeFilterGroup"
          class="close-game"
          src="@/assets/close.svg"
        ></image>
        <view class="all-game">筛选</view>
        <view class="game-list select-list">
          <district-server
            v-model="servers"
            :options="serverOptions"
          ></district-server>
          <attr-filter
            v-for="(options, idx) in attrOptionsGroups"
            :keysa="idx"
            v-model="attrsTemp"
            :options="options"
            @change="addAttr"
          ></attr-filter>
        </view>
        <view class="btn-group">
          <view class="clear" @click="handleResetFilter">清空</view>
          <view class="filter" @click="handleConfirmFilter">筛选</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import API from "@/api/baseUrl";
import { debounce, throttle } from "lodash";
import type { GameAttr, GameRegion, ProductItemType } from "@/types";
import { onLoad } from "@dcloudio/uni-app";
import districtServer from "./components/district-server.vue";
import gameItem from "./components/game-item.vue";
import attrFilter from "./components/attr-filter.vue";
import { onMounted, nextTick } from "vue";
const errTitle = ref("很抱歉，加载失败");
const products = ref<ProductItemType[]>([]);
const onRefresh = () => {};
const gameFilter = ref(null);
const handlePagingScroll = throttle((e: any) => {
  if (gameFilter.value) {
    const el = gameFilter.value.$el.getBoundingClientRect() as any;
    if (isTop.value) {
      el?.y - 47 <= 46 ? (isTop.value = true) : (isTop.value = false);
    } else {
      el?.y <= 46 ? (isTop.value = true) : (isTop.value = false);
    }
  }
}, 20);
const selectGame = ref(0);
const gameLogo = ref("");
const gameName = ref("");
const gameList = ref([]) as any;
const activeItem = ref(0);
const attrsTemp = ref({}) as any;
const morePopupRef = ref();
const searchInput = ref() as any;
const searchValue = ref("");
const isTop = ref(false);
const filterPopupRef = ref();
const paging = ref();
const attrOptions = ref<GameAttr[]>();
const attrOptionsGroups = ref([] as any);
const serverOptions = ref<GameRegion[]>([]);
const sortList = ref([]) as any;
const servers = ref<GameRegion[]>([]);
const popupRef = ref();
const sortItem = ref<{
  name: string;
  index: number | undefined;
  icon: string;
}>({
  name: "",
  index: undefined,
  icon: "down",
});

onMounted(() => {
  nextTick(() => { //进入页面自动获取焦点
    if (searchInput.value) {
      const inputElement =
        searchInput.value.$el.querySelector(".uni-input-input");
      if (inputElement) {
        inputElement.focus();
      }
    }
  });
});

onLoad(async (e) => {
  selectGame.value = e?.id;
  gameLogo.value = e?.logo;
  gameName.value = e?.name;
  activeItem.value = e?.selectId;
  await initGameIcon();
  await initGameTypeInfo();
  getFocus();
});
const getFocus = () => {};
//当前选中的游戏项
const gameItemSelect = computed(() => {
  if (gameList.value.length <= 0) return {};
  gameLogo.value = gameList.value[activeItem.value]?.game_ico;
  return gameList.value[activeItem.value] || {};
});
//当前游戏选中的类型id：选择默认第一个即可
const gameTypeId = computed(() => {
  const TypeId = 1;
  if (!gameItemSelect.value) return TypeId;
  if (
    Array.isArray(gameItemSelect.value?.child_type) &&
    gameItemSelect.value?.child_type.length > 0
  ) {
    const item = gameItemSelect.value?.child_type[0];
    return item?.id ? item?.id : TypeId;
  }
  return TypeId;
});
//当前的游戏id
const gameId = computed(() => {
  const TypeId = 0;
  if (!gameItemSelect.value) return TypeId;
  return gameItemSelect.value?.id ? gameItemSelect.value?.id : TypeId;
});
const showFilter = () => {
  filterPopupRef.value.open();
};
const toDetils = (info: any) => {
  uni.navigateTo({
    url: `/pages/product/index?id=${info?.id}`,
    fail: (err) => {
      console.log(err);
    },
  });
};

const sortContent = (item: any, index: number) => {
  sortItem.value.index = index;
  sortItem.value.name = item.name;
  sortItem.value.icon = item.icon;
  closeDetils();
  paging.value.reload();
};

const addAttr = (obj: any) => {
  let arr = obj.attr.attr_value && JSON.parse(obj.attr.attr_value);
  arr.forEach((item) => {
    Object.keys(attrsTemp.value || {}).map((e) => {
      if (item.children && item.name == attrsTemp.value[e]) {
        attrOptionsGroups.value[0].splice(obj.index + 1, 1);

        let obj2 = {
          ...obj.attr,
          id: `child_${obj.attr.id}_${attrsTemp.value[e]}`,
          attr_name: attrsTemp.value[e],
          attr_value: JSON.stringify(item.children),
        };

        for (const key in attrsTemp.value) {
          if (key.includes("child")) {
            delete attrsTemp.value[key];
          }
        }
        console.log("attrsTemp2", attrsTemp.value);

        attrOptionsGroups.value[0].splice(obj.index + 1, 0, obj2);
      }
    });
  });
};

const closeDetils = () => {
  popupRef.value.close();
};

const closeFilterGroup = () => {
  servers.value = [];
  filterPopupRef.value.close();
};

//游戏列表
const gameFilterList = ref([]) as any;

const initGameTypeInfo = async () => {
  try {
    console.log(gameTypeId.value);
    
    const { data } = await API.get_type_info({
      type_id: gameTypeId.value,
    });
    attrOptions.value = data.data_array;
    serverOptions.value = JSON.parse(data.data_obj || "[]");
    sortList.value = data.base_info.sort_by_list || [];
    const a: GameAttr[] = [];
    const b: GameAttr[] = [];
    attrOptions.value.forEach((item) => {
      if (item.type == "select") {
        b.push(item);
      } else {
        a.push(item);
      }
    });
    attrOptionsGroups.value = [a, b];
    console.log("attrOptionsGroups", attrOptionsGroups.value);
  } catch (err) {
    serverOptions.value = [];
    console.log(err);
  }
};

// 重置过滤
const handleResetFilter = () => {
  attrsTemp.value = {};
  closeFilterGroup();
  paging.value.reload();
};

// 确认过滤
const handleConfirmFilter = () => {
  let arrAttr = Object.keys(attrsTemp.value || {}).map((e) => {
    let obj = {};
    if (!e.includes("child")) {
      obj = {
        id: e,
        value: attrsTemp.value[e],
      };
    } else {
      let ParantId = e.split("_")[1];
      let ParantName = e.split("_")[2];
      obj = {
        id: ParantId,
        value: ParantName,
        child: attrsTemp.value[e],
      };
    }
    return obj;
  });
  paging.value.reload();
};

const back = () => {
  uni.navigateBack();
};
const showDetils = () => {
  popupRef.value.open();
};

const initGameIcon = async () => {
  const res = await API.get_game_all_new({
    game_name: "",
    type: 1,
  });
  gameList.value = res.data;
  await paging.value.reload();
};
const closeGameGroup = () => {
  morePopupRef.value.close();
};

const selectGameGroup = () => {
  morePopupRef.value.open();
};

const toMoreGame = async (info: any, index: number) => {
  activeItem.value = index;
  closeGameGroup();
  // paging.value.reload();
  await initGameIcon();
  await initGameTypeInfo();
  getFocus();
};
const productTotal = ref(0);
const pages = ref<{
  page_now: number;
  page_num: number;
  total: number;
  total_page: number;
}>();
let queryUUID: string; //防止数据错乱
const queryProducts = async (pageNum: number, pageSize: number) => {
  let queryUUIDTemp = (queryUUID = Math.random().toString());
  try {
    const page = {
      page_now: pageNum,
      page_num: pageSize,
    };
    const search = {
      attr: getAttrTemp(),
      bonus_price: "",
      game_id: gameId.value,
      game_zone: servers.value?.map((e) => e.value as any) ?? [],
      goods_type_id: gameTypeId.value,
      is_hire_purchase: "",
      keywords: searchValue.value,
    };
    const sort =
      sortList.value.length > 0
        ? [sortList.value[sortItem.value?.index]?.name_short || ""]
        : [];
    const timestamp = 1734509284;
    const tourist = queryUUIDTemp;
    const res = await API.transform_goods_all2({
      page,
      search,
      sort,
      timestamp,
      tourist,
    });
    // gameFilterList.value = res.data;
    // paging.value.complete(res.data);
    if (queryUUID == queryUUIDTemp) {
      productTotal.value = res?.page?.total;
      paging.value.complete(res.data);
    }
    pages.value = {
      page_now: res?.page?.page_now,
      page_num: res?.page?.page_num,
      total: res?.page?.total,
      total_page: res?.page?.total_page,
    };
    servers.value = [];
    attrsTemp.value = {};
    closeFilterGroup();
  } catch (err) {
    console.error(err);
    const { code, msg } = err;
    errTitle.value = msg || "数据请求频繁,请稍后请求";
    paging.value.complete(false);
  }
};
const getAttrTemp = () => {
  let arrAttr = [];
  arrAttr = Object.keys(attrsTemp.value || {}).map((e) => {
    let obj = {};
    if (!e.includes("child")) {
      obj = {
        id: e,
        value: attrsTemp.value[e],
      };
    } else {
      let ParantId = e.split("_")[1];
      let ParantName = e.split("_")[2];

      obj = {
        id: ParantId,
        value: ParantName,
        child: attrsTemp.value[e],
      };
    }
    return obj;
  });
  arrAttr = arrAttr.filter((item: any) => {
    // 确保'value'属性存在且不为null
    const valueExistsAndNotNull =
      item.hasOwnProperty("value") && item.value !== null;

    // 如果有'child'属性，确保它不为null
    const childExistsAndNotNull =
      !item.hasOwnProperty("child") || item.child !== null;

    // 同时满足两个条件
    return valueExistsAndNotNull && childExistsAndNotNull;
  });
  return arrAttr;
};
</script>

<style lang="scss" scoped>
@media screen and (min-width: 500px) {
  :deep(.z-paging-content) {
    width: 375px;
    max-height: 100vh;
    margin: 0 auto;
  }
  :deep(.zp-page-top){
    width: 375px;
    margin: 0 auto;
  }
}
.no-data {
  width: 100%;
  min-height: 800rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  image {
    width: 200rpx;
    height: 200rpx;
  }
  .not-info {
    color: #9e9e9e;
    font-size: 24rpx;
  }
}
:deep(.zp-scroll-view-super) {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* Internet Explorer 10+ */
  scrollbar-color: transparent transparent; /* Chrome 和 Safari */
  padding: 0px 24rpx;
}
.topcr {
  margin: 0px !important;
  margin-right: 20rpx !important;
  background: #f8f9fb !important;
}
.isctop {
  margin: 0px !important;
  background: #f8f9fb !important;
}
.warpper {
  background: #f8f9fb;
  //   padding: 24rpx 0px;
}
:deep(.warpper) {
  overflow: hidden;
}

.search-box {
  display: flex;
  align-items: center;
}
.logomerbo {
  position: relative;
}

.noread {
  border-radius: 0rpx !important;
  margin-bottom: 0rpx !important;
  padding-top: 0px !important;
}

.active {
  border: 1px solid #fe4644 !important;
  padding: 4rpx;
  border-radius: 15rpx;
}

.tops {
  padding: 25rpx 20rpx;
  padding-right: 25rpx;
  background-color: #fff;
}
.group-content {
  position: relative;
  background: #fff;
  border-radius: 14px 14px 0 0;
  position: relative;
  padding: 20rpx;
  display: flex;
  justify-content: center;
  color: #333333;
  font-size: 30rpx;
  .close-game {
    position: absolute;
    width: 21rpx;
    height: 21rpx;
    right: 50rpx;
    top: 30rpx;
  }
  .all-game {
    width: 100%;
    height: 88rpx;
    text-align: center;
    color: #000000;
    border-bottom: 1px solid #eeeeee;
  }
  .sort-list {
    line-height: 90rpx;
    text-align: center;
  }
}
.my-top {
  margin-top: 20rpx !important;
}
.game-filter {
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  border-radius: 10rpx;
  padding: 25rpx 0rpx;
  margin-bottom: 20rpx;
  .left {
    display: flex;
    align-items: center;
    image {
      margin-left: 5rpx;
    }
  }
  .left,
  .right {
    padding: 0rpx 20rpx;
    font-size: 24rpx;
    color: #666666;
  }
  .left > image,
  .right > image {
    width: 24rpx;
    height: 24rpx;
  }
}
.game-logo {
  width: 48rpx;
  height: 48rpx;
  border-radius: 10rpx;
  margin-left: 10rpx;
  position: relative;
}
.logomerbo::after {
  content: "";
  position: absolute;
  bottom: 0px;
  right: -10rpx;
  width: 24rpx;
  height: 24rpx;
  background-image: url("@/assets/to-game.svg");
  background-size: 100% 100%;
  z-index: 333;
}

.back {
  height: 35rpx;
  width: 35rpx;
  margin-top: 25rpx;
  margin-left: 20rpx;
  display: flex;
  justify-self: center;
  align-items: center;
  image {
    width: 100%;
    height: 100%;
  }
}

.content {
}

.navbar-content {
  flex: 1;
  margin: 0px 24rpx;
  margin-top: 24rpx;
  height: 60rpx;
  background-color: #fff;
  padding: 10rpx 0rpx;
  border-radius: 10rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .search {
    height: 100%;
    flex: 1;
    padding-left: 20rpx;
    letter-spacing: 3rpx;
    font-size: 26rpx;
  }
  .search::placeholder {
    color: #999999;
  }
  .search-icon {
    width: 100rpx;
    margin-right: 10rpx;
    margin-left: 10rpx;
    height: 100%;
    background: #fe4644;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 10rpx;
    image {
      width: 50%;
      height: 50%;
    }
  }
}

.group-content-game {
  position: relative;
  max-height: 900rpx;
  width: 100%;
  background: #fff;
  border-radius: 14px 14px 0 0;
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* Internet Explorer 10+ */
  scrollbar-color: transparent transparent; /* Chrome 和 Safari */
  color: #333333;
  font-size: 30rpx;
  .btn-group {
    position: fixed;
    bottom: 0px;
    width: 100%;
    font-size: 28rpx;
    display: flex;
    height: 80rpx;
    background-color: #fff;
    view {
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 10rpx;
      margin-right: 40rpx;
    }
    .clear {
      width: 200rpx;
      background: #f8f9fb;
      margin-left: 20rpx;
    }
    .filter {
      flex: 1;
      color: #fff;
      background: #fe4644;
    }
  }
  .select-list {
    padding: 20rpx 20rpx !important;
    margin-bottom: 80rpx;
  }
  .game-list {
    margin-top: 88rpx;
    padding: 20rpx 50rpx;
    width: calc(100% - 50rpx);
    display: flex;
    flex-wrap: wrap;
    gap: 65rpx;
    .item-game {
      .game-ico {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4rpx;
        border: 1px solid #ffff;
      }
      image {
        width: 72rpx;
        height: 72rpx;
        border-radius: 10rpx;
      }
      .game-name-value {
        font-size: 20rpx;
        color: #333333;
        overflow: hidden; /* 隐藏溢出的文本 */
        white-space: nowrap; /* 文本不换行 */
        text-overflow: ellipsis; /* 溢出的文本显示为省略号 */
        text-align: center;
        width: 80rpx;
      }
    }
  }
  .close-game {
    position: fixed;
    width: 21rpx;
    height: 21rpx;
    right: 50rpx;
    top: 30rpx;
    z-index: 33;
  }
  .all-game {
    width: 100%;
    height: 88rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #000000;
    border-bottom: 1px solid #eeeeee;
    position: fixed;
    border-top-right-radius: 20rpx;
    border-top-left-radius: 20rpx;
    background-color: #fff;
    z-index: 22;
  }
  .sort-list {
    line-height: 90rpx;
  }
}
</style>
